import sys
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *


def maya_main_window():
    import maya.OpenMayaUI as omui
    from shiboken6 import wrapInstance
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(int(main_window_ptr), QWidget)


class ModernWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Tabbed Interface")
        self.resize(600, 400)  # 更推荐用resize而不是setGeometry

        # 创建中心部件（关键修复）
        central_widget = QWidget()
        self.setCentralWidget(central_widget)  # QMainWindow必须设置中心部件

        # 主布局
        main_layout = QVBoxLayout(central_widget)  # 布局附加到中心部件

        # 创建选项卡组件
        tab_widget = QTabWidget()

        # 第一个选项卡
        tab1 = QWidget()
        tab1_layout = QVBoxLayout(tab1)
        button1 = QPushButton("Button 1")
        button2 = QPushButton("Button 2")

        # 按钮样式
        button_style = """
        QPushButton {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            margin: 5px;
        }
        QPushButton:hover {
            background-color: #45a049;
        }
        """
        button1.setStyleSheet(button_style)
        button2.setStyleSheet(button_style)

        tab1_layout.addWidget(button1)
        tab1_layout.addWidget(button2)
        tab1_layout.addStretch()

        # 第二个选项卡
        tab2 = QWidget()
        tab2.setLayout(QVBoxLayout())

        # 添加选项卡
        tab_widget.addTab(tab1, "Tab 1")
        tab_widget.addTab(tab2, "Tab 2")

        # 主布局添加组件
        main_layout.addWidget(tab_widget)

        # 整体样式（修正版）
        self.setStyleSheet("""
        QMainWindow {
            background-color: #f0f0f0;
        }
        QTabWidget::pane {
            border: 1px solid #d0d0d0;
            background: white;
            border-radius: 5px;
            margin: 5px;
        }
        QTabBar::tab {
            background: #e8e8e8;
            color: #404040;
            padding: 8px 16px;
            border: 1px solid #d0d0d0;
            border-bottom: none;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
        }
        QTabBar::tab:selected {
            background: white;
            color: #4CAF50;
            border-color: #4CAF50;
        }
        """)


def run_in_maya():
    # 确保只有一个QApplication实例
    app = QApplication.instance() or QApplication(sys.argv)

    # 创建窗口时设置窗口标志
    window = ModernWindow(parent=maya_main_window())
    window.setWindowFlags(Qt.Window)  # 确保窗口类型正确

    # 防止Maya关闭时崩溃
    window.setAttribute(Qt.WA_DeleteOnClose)

    window.show()
    return window


# 在Maya中调用：
# run_in_maya()